package com.baibei.ebec.moments.activity;

import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.baibei.ebec.home.R;
import com.baibei.ebec.home.R2;
import com.baibei.ebec.moments.adapter.MomentsHomeAdapter;
import com.baibei.ebec.sdk.ApiConstant;
import com.baibei.model.UserInfo;
import com.baibei.ui.AppUI;
import com.blankj.utilcode.utils.ToastUtils;
import com.google.gson.Gson;
import com.rae.swift.session.SessionManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.onekeyshare.OnekeyShare;
import cn.sharesdk.onekeyshare.ShareContentCustomizeCallback;
import okhttp3.Call;
import okhttp3.FormBody;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

@Route(path = "/welfare/moment/home")
public class MomentsHomeActivity extends AppCompatActivity {

    @BindView(R2.id.tv_hot)
    TextView tvHot;
    @BindView(R2.id.tv_new)
    TextView tvNew;
    @BindView(R2.id.tv_follow)
    TextView tvFollow;
    @BindView(R2.id.bar_hot)
    TextView barHot;
    @BindView(R2.id.bar_new)
    TextView barNew;
    @BindView(R2.id.bar_follow)
    TextView barFollow;
    @BindView(R2.id.rv)
    RecyclerView rv;
    private int red;
    private int black;
    private int white;
    private MomentsHomeAdapter mAdapter;
    private ArrayList<JSONObject> hotArr;
    //默认初始页数
    private int page = 1;
    private JSONObject json;
    private long userId;
    private boolean isRvSetAdapterAlready;
    //默认类型为热门
    private String articleType = "1";
    private ArrayList<JSONObject> newArr;
    private ArrayList<JSONObject> followArr;
    //记录是否已经加载完所有数据
    private boolean isNoMoreData;
    private int UPDATE_DATA = 1;
    private int THUMB = 2;
    private int clickCount;
    private int clickPosition;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_moments_home);
        ButterKnife.bind(this);
        red = getResources().getColor(R.color.red);
        black = getResources().getColor(R.color.black);
        white = getResources().getColor(R.color.white);

        UserInfo userInfo = SessionManager.getDefault().getUser();
        userId = (long) userInfo.getUserId();
        //热门
        hotArr = new ArrayList<>();
        //最新
        newArr = new ArrayList<>();
        //关注
        followArr = new ArrayList<>();

        initView(hotArr);

        getData(articleType, page);
    }

    Handler handler = new Handler();

    //加载和刷新数据的runnable
    Runnable r1 = new Runnable() {
        @Override
        public void run() {

            AppUI.dismiss();

            if (!"0".equals(json.optString("code"))){
                ToastUtils.showShortToast(json.optString("message"));
                return;
            }
            ArrayList<JSONObject> list = new ArrayList<>();
            try {
                JSONArray data = json.optJSONArray("data");
                for (int i = 0; i < data.length(); i++) {
                    list.add(data.getJSONObject(i));
                }
            } catch (JSONException e) {
                e.printStackTrace();
            }

            //判断类型，决定把数据加载到哪个集合里
            ArrayList<JSONObject> jsonArr = getWhichArr();

            if (list != null) {
                jsonArr.addAll(list);
                if (!isRvSetAdapterAlready) {
                    LinearLayoutManager llm = new LinearLayoutManager(getApplicationContext());
                    rv.setLayoutManager(llm);
                    mAdapter = new MomentsHomeAdapter(jsonArr);
                    rv.setAdapter(mAdapter);
                    isRvSetAdapterAlready = true;
                }

                //RecyclerView的item和item内部控件点击事件
                mAdapter.setOnRecyclerViewItemClickListener(new MomentsHomeAdapter.onRecyclerViewItemClickListener() {
                    @Override
                    public void onClick(View view, MomentsHomeAdapter.ViewName viewName, int position) {
                        switch (viewName) {
                            case ITEM:
                                toBBSDetail(position);
                                break;
                            case THUMB:
                                performThumb(position);
                                break;
                            case COMMENT:
                                toBBSDetail(position);
                                break;
                            case USERNAME:
                                //跳转该用户个人中心，暂不处理
                                break;
                            case SHARE:
                                toShare(position);
                        }
                    }
                });
                if (mAdapter != null) {
                    mAdapter.notifyDataSetChanged();
                }
            }
        }
    };

    //点赞后页面ui更改的runnable
    Runnable r2 = new Runnable() {
        @Override
        public void run() {

            AppUI.dismiss();

            ToastUtils.showShortToast(json.optString("message"));
            if (!"0".equals(json.optString("code"))) {
                return;
            }
            String s = json.optString("state");
            switch (s) {
                case "0":
                    clickCount--;
                    //更新点赞数和点赞图标
                    updateClickCount("0");
                    break;
                case "1":
                    clickCount++;
                    updateClickCount("1");
            }
        }
    };

    private void updateClickCount(String state) {
        JSONObject jsonObject = getWhichArr().get(clickPosition);
        try {
            jsonObject.put("clickCount", clickCount);
            jsonObject.put("state", state);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        getWhichArr().set(clickPosition, jsonObject);
        mAdapter.notifyDataSetChanged();
    }

    private void toShare(int position) {
        JSONObject jsonObject = getWhichArr().get(position);
        final String shareUrl = jsonObject.optString("shareUrl");
        final String contents = jsonObject.optString("contents");
        OnekeyShare oks = new OnekeyShare();
        oks.setTitle("点点淘金点点圈");
        oks.setTitleUrl(shareUrl);
        oks.setText(contents);
        oks.setUrl(shareUrl);
        Bitmap image = null;
        AssetManager assets = getResources().getAssets();
        try {
            InputStream is = assets.open("logo.png");
            image = BitmapFactory.decodeStream(is);
            is.close();
            oks.setImageData(image);
        } catch (IOException e) {
            e.printStackTrace();
        }

        oks.setShareContentCustomizeCallback(new ShareContentCustomizeCallback() {
            @Override
            public void onShare(Platform platform, Platform.ShareParams shareParams) {
                if ("ShortMessage".equals(platform.getName())) {
                    shareParams.setText("点点淘金点点圈：" + shareUrl);
                }
//                if ("QQ".equals(platform.getName())) {
//                    shareParams.setTitle("点点淘金点点圈");
//                    shareParams.setText(contents);
//                    Log.i("jsonhhhhqq",shareUrl);
//                    shareParams.setTitleUrl(shareUrl);
//                    shareParams.setUrl(shareUrl);
//                }

            }
        });
        oks.show(this);
    }

    private void performThumb(int position) {
        String url = ApiConstant.API_BASE_URL + "ddq/api/v1/dianzan/addDianzan";
        JSONObject jsonObject = getWhichArr().get(position);
        clickPosition = position;
        HashMap<String, Object> map = new HashMap<>();
        map.put("userId", userId);
        map.put("operationId", jsonObject.optLong("bbsId"));
        map.put("state", jsonObject.optString("state"));
        clickCount = jsonObject.optInt("clickCount");
        netRequest(url, map, THUMB);
    }

    private void toBBSDetail(int position) {
        JSONObject jsonObject = getWhichArr().get(position);
        Intent intent = new Intent(MomentsHomeActivity.this, MomentsDetailActivity.class);
        intent.putExtra("content", jsonObject.toString());
        intent.putExtra("position", position);
        //fromType，跳转来源的类型，1是指从点点圈首页的帖子列表跳转过来的
        intent.putExtra("fromType",1);
        startActivityForResult(intent, 1);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode == 1) {
            //跳转帖子详情页，返回列表页时要将详情页改变的点赞数，点赞状态，评论数带回来并刷新
            int clickCount = data.getExtras().getInt("clickCount");
            int commentCount = data.getExtras().getInt("commentCount");
            String state = data.getExtras().getString("state");
            int position = data.getExtras().getInt("position");
            JSONObject jsonObject = getWhichArr().get(position);
            try {
                jsonObject.put("clickCount", clickCount);
                jsonObject.put("commentCount", commentCount);
                jsonObject.put("state", state);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Log.i("jsonhhhhr", "there");
            mAdapter.notifyDataSetChanged();
        } else if (resultCode == 2) {
            //发帖成功，刷新new
            tvNew.performClick();
        }
    }

    private ArrayList<JSONObject> getWhichArr() {
        switch (articleType) {
            case "1":
                return hotArr;
            case "2":
                return newArr;
            case "3":
                return followArr;
        }
        return null;
    }

    private void initView(final ArrayList<JSONObject> arrayList) {
        rv.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                RecyclerView.LayoutManager layoutManager = rv.getLayoutManager();
                int lastVisiablePosition = -1;
                if (layoutManager instanceof LinearLayoutManager) {
                    LinearLayoutManager llm = (LinearLayoutManager) layoutManager;
                    lastVisiablePosition = llm.findLastCompletelyVisibleItemPosition();
                }

                //判断是否已经滑到底页
                if (lastVisiablePosition == arrayList.size() - 1) {
                    //判断是否已经没有更多数据可加载
                    if (json.has("count") && json.optInt("count") < 10) {
                        ToastUtils.showShortToast("没有更多数据了");
                        isNoMoreData = true;
                        return;
                    }
                    if (!isNoMoreData) {
                        AppUI.loading(MomentsHomeActivity.this);
                        page += 1;
                        getData(articleType, page);
                    }
                }
            }

            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
            }
        });
    }

    private void getData(String articleType, int pageNo) {
        String url = ApiConstant.API_BASE_URL + "ddq/api/v1/article/findArticleList";
        HashMap<String, Object> map = new HashMap<>();
        map.put("articleType", articleType);
        map.put("pageNo", pageNo);
        map.put("userId", userId);
        netRequest(url, map, UPDATE_DATA);
    }

    @OnClick({R2.id.iv_back, R2.id.tv_hot, R2.id.tv_new, R2.id.tv_follow})
    public void onViewClicked(View view) {
        if (view.getId() == R.id.iv_back) {
            finish();
        } else if (view.getId() == R.id.tv_hot) {
            setAllTabUnchosen();
            tvHot.setTextColor(red);
            barHot.setBackgroundColor(red);
            reload("1");
        } else if (view.getId() == R.id.tv_new) {
            setAllTabUnchosen();
            tvNew.setTextColor(red);
            barNew.setBackgroundColor(red);
            reload("2");
        } else if (view.getId() == R.id.tv_follow) {
            setAllTabUnchosen();
            tvFollow.setTextColor(red);
            barFollow.setBackgroundColor(red);
            reload("3");
        }
    }

    private void reload(String type) {
        switch (type) {
            case "1":
                initView(hotArr);
                break;
            case "2":
                initView(newArr);
                break;
            case "3":
                initView(followArr);
                break;
        }
        //所有数据清空
        hotArr.clear();
        newArr.clear();
        followArr.clear();
        //重新设置类型
        articleType = type;
        //页数计数重归为1
        page = 1;
        //是否已经加载过adapter设置为否
        isRvSetAdapterAlready = false;
        //是否加载完所有数据设置为否
        isNoMoreData = false;

        getData(type, page);
    }

    private void netRequest(final String url, final Map<String, Object> map, final int type) {
        AppUI.loading(MomentsHomeActivity.this);
        new Thread(new Runnable() {
            @Override
            public void run() {
                Gson gson = new Gson();
                String s = gson.toJson(map);
                Log.i("jsonhhhh", s);
                RequestBody requestBody = FormBody.create(MediaType.parse("applicaiton/json; charset=utf-8"), s);
                OkHttpClient client = new OkHttpClient();
                Request request = new Request.Builder()
                        .post(requestBody)
                        .url(url)
                        .build();
                Call call = client.newCall(request);
                try {
                    Response response = call.execute();
                    json = new JSONObject(response.body().string());
                    Log.i("jsonhhhh", json.toString());
                    handler.post(type == UPDATE_DATA ? r1 : r2);
                } catch (IOException e) {
                    AppUI.dismiss();
                    e.printStackTrace();
                } catch (JSONException e) {
                    AppUI.dismiss();
                    e.printStackTrace();
                }
            }
        }).start();
    }

    private void setAllTabUnchosen() {
        tvHot.setTextColor(black);
        tvNew.setTextColor(black);
        tvFollow.setTextColor(black);
        barHot.setBackgroundColor(white);
        barNew.setBackgroundColor(white);
        barFollow.setBackgroundColor(white);
    }

    @OnClick(R2.id.iv_send)
    public void onSendClicked() {
        Intent intent = new Intent(MomentsHomeActivity.this, BBSEditorActivity.class);
        startActivityForResult(intent, 2);
//        startActivity(intent);
    }

    @OnClick(R2.id.iv_mycenter)
    public void onMyCenterClicked() {
        Intent intent = new Intent(MomentsHomeActivity.this, MomentsInfoActivity.class);
        intent.putExtra("type", 1);
        startActivity(intent);
    }
}
